import { useCallback, useRef, useState } from "react";
import { useRefNow } from "./useRefNow";


export function useRefState<T>(initial: T | (() => T)) {
  const init = typeof initial !== 'function' ? initial : (initial as () => T)();
  const ref_state = useRef<T>(init);
  const [state, __set_state] = useState<T>(init);
  const ref_set_state = useRefNow(__set_state)

  const set_state = useCallback<typeof __set_state>((action) => {
    if (typeof action !== 'function')
      return ref_set_state.current(ref_state.current = action)
    const update = action as ((prevState: T) => T)
    return ref_set_state.current((prev) => ref_state.current = update(prev))
  }, [])

  return [state, set_state, ref_state] as const;
}
